<?php 
class Captcha{

	public static function create($str='', $font_size=74){

		$str_arr = str_split($str);
		$height = $font_size * 2;
		$width = count($str_arr) * $font_size;
		$im = imagecreatetruecolor($width, $height);

		$font = __DIR__ . '/font/font.otf';

		// 填充背景
		$color = imagecolorallocate($im, 255, 255, 255);
		imagefill($im, 0, 0, $color);

		// 版权
		$arr = array_reverse(str_split('Powered By XieLei!'));
		$x_end=$width - $font_size/5;
		foreach ($arr as $value) {
			$color = imagecolorallocate($im, 200, 200, 200);
			imagettftext($im, $font_size/5, -15, $x_end, $height*0.97, $color, $font, $value);
			$x_end -= $font_size/5;
		}

		// 画验证字符串
		$step = $width/(count($str_arr)+1);
		$x_start=$step - $font_size*0.3;
		foreach ($str_arr as $value) {
			$color = imagecolorallocate($im, mt_rand(0,188), mt_rand(0,188), mt_rand(0,188));
			imagettftext($im, mt_rand($font_size*0.8, $font_size*1.2), mt_rand(-10,10), $x_start, mt_rand($font_size*1.4, $font_size*1.6), $color, $font, $value);
			$x_start += $step;
		}

		//添加需要验证的字母或者数字
		$rand_str = "qwertyuiopasdfghjklzxcvbnm1234567890";
		$count = count($str_arr)*2;
		for($i = 0; $i<$count; $i++){                        
			$pos = mt_rand(0,strlen($rand_str)-1);
			$color = imagecolorallocate($im, mt_rand(155,255), mt_rand(155,255), mt_rand(155,255));
			imagettftext($im, mt_rand($font_size*0.4, $font_size*0.8), mt_rand(-90, 90), mt_rand(0, $width), mt_rand(0, $font_size*2), $color, $font, $rand_str[$pos]);
		}

		// 干扰线
		$count = $font_size/4;
		for($i=0;$i<$count;$i++){
			$color = imagecolorallocate($im,mt_rand(100,255),mt_rand(100,255),mt_rand(100,255));
			imageline($im, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $color);
		}
		
		// 噪点
		$count = $font_size*3;
		for($i=0;$i<$count;$i++){
			$color = imagecolorallocate($im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
			imagesetpixel($im, mt_rand(0, $width), mt_rand(0, $height), $color);
		}

		ob_start();
		imagepng($im);
		$content = ob_get_clean();
		imagedestroy($im);
		return $content;
	}

}